﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace FaceAppClient.Baidu.FaceAPI
{
    public static class AccessToken
    {
        // 调用getAccessToken()获取的 access_token建议根据expires_in 时间 设置缓存
        // 返回token示例
        //public static String TOKEN = "24.adda70c11b9786206253ddb70affdc46.2592000.1493524354.282335-1234567";

        // 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
        private static String clientId = "2pq0I58jp5lMwKVUd08xGojI";
        // 百度云中开通对应服务应用的 Secret Key
        private static String clientSecret = "SSP592rOfyZzRoh3DXGDx5iWWUIOMq8i";

        public static String getAccessToken()
        {
            string token = System.Configuration.ConfigurationManager.AppSettings["access_token"];
            string limit = System.Configuration.ConfigurationManager.AppSettings["access_token_limit"];
            bool flag = true;
            String result = "";            
            System.Configuration.Configuration cfa = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
            if (string.IsNullOrEmpty(token))
            {
                flag = false;                
            }
            else if (string.IsNullOrEmpty(limit))
            {
                flag = false;
            }
            else if (!string.IsNullOrEmpty(limit))
            {
                DateTime now = DateTime.Now;
                TimeSpan ts = now - Convert.ToDateTime(limit);
                int sub = ts.Days;
                if (sub > 29)
                    flag = false;
            }
            if (flag)
            {
                result = token;
            }
            else
            {
                String authHost = "https://aip.baidubce.com/oauth/2.0/token";
                HttpClient client = new HttpClient();
                List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
                paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
                paraList.Add(new KeyValuePair<string, string>("client_id", clientId));
                paraList.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
                HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
                result = response.Content.ReadAsStringAsync().Result;
                cfa.AppSettings.Settings["access_token"].Value = result;
            }
            cfa.AppSettings.Settings["access_token_limit"].Value = DateTime.Now.ToString();
            cfa.Save(System.Configuration.ConfigurationSaveMode.Modified);
            System.Configuration.ConfigurationManager.RefreshSection("appSettings");
            return result;
        }
    }
}
